package org.singularity.io;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public abstract class StringUtil {
	
	private StringUtil(){}
	
	final static char[] digits = {
    	'0' , '1' , '2' , '3' , '4' , '5' ,
    	'6' , '7' , '8' , '9' , 'a' , 'b' ,
    	'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
    	'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
    	'o' , 'p' , 'q' , 'r' , 's' , 't' ,
    	'u' , 'v' , 'w' , 'x' , 'y' , 'z'
        };
	
	public static String toHexString(byte b) {
		return "" + digits[(0xF & (b >> 4))] + digits[(0xF & (b))];
	}
	
	public static String toHexString(byte[] bytes) {
		StringBuffer sb = new StringBuffer(bytes.length * 2);
		for (byte b : bytes) {
		  sb.append(digits[(0xF & (b >> 4))]); 
		  sb.append(digits[(0xF & (b))]);
		}
		return sb.toString();
	}
	
	public static String readFullyUTF8(File aSource) throws IOException
	{
		String strRead = new String(readBytesFully(aSource), "UTF-8");
		return strRead;
	}
	public static String readFullyUTF8(InputStream fis) throws IOException
	{
		String strRead = new String(readBytesFully(fis), "UTF-8");
		return strRead;
	}
	
	public static byte[] readBytesFully(File aSource) throws IOException
	{
		InputStream fis = null;
		try
		{
			fis = new FileInputStream(aSource);
			return readBytesFully(fis);
		}
		finally
		{
			if(fis!=null)
				try
			{
					fis.close();
			}
			catch (IOException e)
			{
				throw e;
			}
		}
	}
	public static byte[] readBytesFully(InputStream fis) throws IOException
	{
		
			fis = new BufferedInputStream(fis);
		
			ByteArrayOutputStream data = new ByteArrayOutputStream(4 * 1024);
			
			int avail = 0;
			while ((avail = fis.available()) != 0)
			{
				byte[] buff = new byte[avail];
				int actualLenght = fis.read(buff);
				data.write(buff, 0, actualLenght);
			}
			
			return data.toByteArray();
		
	}

}
